//
//  CLPostContentViewController.m
//  CL1024
//
//  Created by liu nian on 13-1-29.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CLPostContentViewController.h"
#import "TFHpple.h"
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "CLTool.h"
#import "MBProgressHUD.h"
#import "ProgressBarInfo.h"
#import "CLConst.h"
#import "CLImage.h"
#import "ASINetworkQueue.h"
#import "CLWebViewController.h"
#import "UIImage+Scale.h"
#import "CLTextLayoutLabel.h"
#import "UIImage+animatedGIF.h"
#import "PrettyKit.h"
#import "CLReplyPostsViewController.h"
#import "CLAppDelegate.h"

//楼主贴内容获取规则
#define TOP_POST_CONTENT_QUERY @"(//div[@class='tpc_content'])[1]//img|(//div[@class='tpc_content'])[1]//text()|(//div[@class='tpc_content'])[1]//input"
//回帖内容获取规则
#define REPLAY_POST_CONTENT_QUERY @"(//div[@class='tpc_content'])[position()>1]/text()"
//楼主名获取规则
#define TOP_AUTHOR_NAME_QUERY @"(//div[@class='t t2'])[1]//font//text()"

#define TOP_POSTED_TIME_QUERY @"(//div[@class='tipad'])[1]/text()[last()-1]"

#define ITEM_ATTRIBUTE @"attribute"
#define ITEM_CONTENT @"content"
#define ITEM_HEIGHT @"height"
#define ITEM_IMAGE @"image"
#define ITEM_IMAGEVIEW @"imageview"
#define ITEM_DOWNLOAD_STATE @"downstate"
#define ITEM_DOWNLOAD_PROGRCESSBAR @"progrcessBar"
#define ITEM_ISGIF @"isgif"

#define DOWNLOADING @"donwloading"
#define DOWNLOADOVER @"over"
#define DOWNLOADBEGIN @"begin"
#define DOWNLOADFAILS @"fails"

#define LABLE_CONTENT_WIDTH 305 //文字内容占用的宽度

#define defaultImageFrame CGRectMake(20.f, 10.f, 150.0f, 150.0f) //默认图片占用的Frame

@interface CLPostContentViewController (){
    BOOL hiddenNavagationBar;
}
@property (nonatomic,retain) NSString *louzhuName;
@property (nonatomic,retain) NSString *postedTime;
@property (nonatomic,retain) NSMutableDictionary *imageViewDic;
@property (nonatomic,retain) MBProgressHUD *progress;
@property (nonatomic,retain) ASINetworkQueue *queue;
@property (nonatomic,retain) NSIndexPath *currentSelectIndex;

@property (retain, nonatomic) IBOutlet PrettyToolbar *toolbar;

@property (retain, nonatomic) IBOutlet PrettyNavigationBar *cNavigationBar;
@property (retain,nonatomic) NSData *postContentData; //转换成Data形式的帖子页内容
@property (retain,nonatomic) NSMutableArray *replayPostArray;

//读取帖子内容的方法
-(void)readPostContent;
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView;
-(IBAction)replayPostAction;
@end

@implementation CLPostContentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        hiddenNavagationBar = YES;
        self.imageViewDic = [NSMutableDictionary dictionary];
        self.postContentArray = [NSMutableArray array];
        self.replayPostArray = [NSMutableArray array];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.cNavigationBar setHidden:NO];
    
    //工具栏颜色设置
    self.toolbar.topLineColor =  [UIColor colorWithHex:0x004D7F];
    self.toolbar.gradientStartColor = [UIColor colorWithHex:0x006699];
    self.toolbar.gradientEndColor = [UIColor colorWithHex:0x000000];
    self.toolbar.bottomLineColor = [UIColor colorWithHex:0x000000];
    self.toolbar.tintColor =[UIColor colorWithHex:0x006699];

    //打开原始页按钮
    
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBarButton.frame = CGRectMake(10,0, 22, 22);
    rightBarButton.imageView.contentMode = UIViewContentModeCenter;
    [rightBarButton setBackgroundImage:[UIImage imageNamed:@"eye.png"] forState:UIControlStateNormal];
    rightBarButton.showsTouchWhenHighlighted = YES;
    [rightBarButton addTarget:self action:@selector(openWebview) forControlEvents:UIControlEventTouchUpInside];
    
    /*
    UILabel *rightButtonLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 5, 100, 20)];
    rightButtonLabel.text = @"网页浏览";
    rightButtonLabel.font = [UIFont systemFontOfSize:14];
    rightButtonLabel.backgroundColor = [UIColor clearColor];
    rightButtonLabel.textColor = [UIColor whiteColor];
    [rightBarButton insertSubview:rightButtonLabel atIndex:0];
    [rightButtonLabel release];
    */
    
    
    UIBarButtonItem *rightMenuItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButton];
//    self.navigationItem.rightBarButtonItem = rightMenuItem;
    self.cNavigationBar.topItem.rightBarButtonItem = rightMenuItem;
    [rightMenuItem release];
    
   //导航栏标题
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = kHSCNBoldFont18;
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.text = self.title;
    self.cNavigationBar.topItem.titleView = label;
//    self.navigationItem.titleView = label;
    [label sizeToFit];
    
    //设置网络请求队列
    ASINetworkQueue *myqueue = [[ASINetworkQueue alloc] init];
    [myqueue setShowAccurateProgress:YES];
    [myqueue go];
    self.queue = myqueue;
    [myqueue release];
    
    //去掉cell的灰线
//    self.postsTableView.frame = [[UIScreen mainScreen] bounds];
    
    self.postsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.postsTableView.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
    
    // 帖子标题
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 80)] ;
    headerLabel.lineBreakMode = UILineBreakModeWordWrap;
    headerLabel.numberOfLines = 0;
    headerLabel.adjustsFontSizeToFitWidth = YES;
    headerLabel.text = self.postTitle;
    headerLabel.shadowColor = [UIColor grayColor];
    headerLabel.shadowOffset = CGSizeMake(0.1, 0.1);
    headerLabel.font = kHSCNBoldFont18;
    headerLabel.textColor = [UIColor orangeColor];
    headerLabel.backgroundColor = [UIColor clearColor];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 90, 300, 1)];
    line.backgroundColor = [UIColor lightGrayColor];
    
    self.postsTableView.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
    [self.postsTableView.tableHeaderView addSubview:headerLabel];
    [self.postsTableView.tableHeaderView addSubview:line];
//    [self.postsTableView.tableHeaderView addSubview:headerLabel];
//    [self.postsTableView.tableHeaderView addSubview:tableHeaderView] ;
    [headerLabel release];
    [line release];
    
    self.postsTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
    
    //查看回帖功能还不完美，暂时禁用
    [self.repostButton setEnabled:NO];
    
    //添加手势
    UITapGestureRecognizer *TapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handelPan:)];
    TapGes.numberOfTapsRequired = 2 ;
    TapGes.delegate = self;
    [self.postsTableView addGestureRecognizer:TapGes];
    [TapGes release];
    
    self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NSThread detachNewThreadSelector:@selector(readPostContent) toTarget:self withObject:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    //隐藏默认的导航栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    hiddenNavagationBar = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
 
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 
#pragma mark  UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.postContentArray count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        
        CLTextLayoutLabel *label = [[[CLTextLayoutLabel alloc] initWithFrame:CGRectZero] autorelease];
        label.tag = 1102;
        label.font = kHSCNBoldFont16;
//        label.font = systemFont;
        label.textColor = [UIColor colorWithHex:0x454545];
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.shadowColor = [UIColor lightGrayColor];
        label.backgroundColor = [UIColor clearColor];
        label.shadowOffset = CGSizeMake(0.1, 0.1);
        label.numberOfLines = 0;
        label.opaque = NO;
        [label setLinesSpacing:8.0f];
        [cell.contentView addSubview:label];
        
        UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
        imageView.tag = 1101;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = defaultImageFrame;
        imageView.image = [UIImage imageNamed:image_placeholder];
          [cell.contentView addSubview:imageView];
        //取消选中cell时的背景色
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
         
      
        NSMutableDictionary *dic = [self.postContentArray objectAtIndex:[indexPath row]];
    //图片部分的显示处理
    if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"image"]) {
        UIImageView *imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
        
        //从图片中移除下载进度条
        UIProgressView *progressView = (UIProgressView *)[imageview viewWithTag:1103];
        [progressView removeFromSuperview];
        
        imageview.frame = defaultImageFrame;
        imageview.image = [UIImage imageNamed:image_placeholder];
        imageview.hidden = NO;
        UILabel *label = (UILabel *)[cell.contentView viewWithTag:1102];
        label.frame = CGRectZero;
        
        cell.textLabel.text = nil;
        imageview.hidden = NO;
        NSString *downloadState = (NSString *)[dic objectForKey:ITEM_DOWNLOAD_STATE];
       
        //开始下载
        
        if ([downloadState isEqualToString:DOWNLOADBEGIN]) {
            if (self.postsTableView.dragging == NO && self.postsTableView.decelerating == NO)
            {
                NSString *imageUrl = [dic objectForKey:ITEM_CONTENT];
                NSURL *url =[NSURL URLWithString:imageUrl];
                //是否是gif图
                if ([[[url pathExtension] lowercaseString] isEqualToString:@"gif"]) {
                    [dic setValue:@"1" forKey:ITEM_ISGIF];
                }
                
                UIProgressView *progressView = [[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar] autorelease];
                progressView.hidden=YES;
                progressView.tag= 1103;
                progressView.frame = CGRectMake(28 ,imageview.frame.size.height / 2 + 10,100,25);
                progressView.progress=0.0f;
                [progressView setHidden:NO];
                [imageview addSubview:progressView];
                //保存此imageview
                [dic setValue:imageview forKey:ITEM_IMAGEVIEW];
                //标识此图片进入下载中
                [dic setValue:DOWNLOADING forKey:ITEM_DOWNLOAD_STATE];
                [dic setValue:progressView forKey:ITEM_DOWNLOAD_PROGRCESSBAR];
                [self.postContentArray replaceObjectAtIndex:[indexPath row] withObject:dic];
                //============ASIHTTPRequest==========
                ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
                request.delegate = self;
                request.downloadProgressDelegate = progressView;
                [request setUserInfo:[NSDictionary dictionaryWithObject:indexPath forKey:@"index"]];
                [self.queue addOperation:request];
                //================================
 
            }
       }
         

            //图片下载中的处理
            if ([downloadState isEqualToString:DOWNLOADING]) {
//                imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
                imageview = [dic objectForKey:ITEM_IMAGEVIEW];
                imageview.frame = defaultImageFrame;
                UIProgressView *progressBar = [dic objectForKey:ITEM_DOWNLOAD_PROGRCESSBAR];
                [imageview addSubview:progressBar];
                progressBar.hidden = NO;
                imageview.image = [UIImage imageNamed:image_placeholder];
            }
            //图片下载完或下载失败
            if ([downloadState isEqualToString:DOWNLOADOVER] || [downloadState isEqualToString:DOWNLOADFAILS]) {
                imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
                UIImage *downloadImage = [dic objectForKey:ITEM_IMAGE];
                if (downloadImage != nil) {
                    float width = [[UIScreen mainScreen] bounds].size.width;
                    float height = [(NSNumber *)[dic objectForKey:ITEM_HEIGHT] floatValue];
                    imageview.frame = CGRectMake(0.0f, 10.0f, width, height);
                    imageview.image  = downloadImage;
                }
            }
       //图片下载失败
        if ([downloadState isEqualToString:DOWNLOADFAILS]) {
            imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
            imageview.image = [UIImage imageNamed:@"downloadFails.png"];
        }
    }
    
    
  //文字部分的显示处理
    if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"text"]) {
        
        UIImageView *imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
         imageview.hidden = YES;
        //清空cell上原有的progressView
        UIProgressView *progressBar = (UIProgressView *)[cell.contentView viewWithTag:1103];
        if (progressBar != nil) {
            [progressBar removeFromSuperview];
        }

        
        NSString *text = [dic objectForKey:ITEM_CONTENT];
//        UILabel *label = (UILabel *)[cell.contentView viewWithTag:1102];
        CLTextLayoutLabel *label = (CLTextLayoutLabel *)[cell.contentView viewWithTag:1102];
        CGFloat labelWidth = LABLE_CONTENT_WIDTH;
        CGFloat labelHeight =  [(NSNumber *)[dic objectForKey:ITEM_HEIGHT] floatValue]; 
        [label setFrame:CGRectMake(10, 10, labelWidth, labelHeight)];
        label.text = text;
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSMutableDictionary *dic = [self.postContentArray objectAtIndex:[indexPath row]];
    if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"image"]) {
        if ([dic objectForKey:ITEM_HEIGHT] != nil) {
            return [(NSNumber *)[dic objectForKey:ITEM_HEIGHT] floatValue] + 10;
        }else{
            return 160;
        }
           }else{
               if ([dic objectForKey:ITEM_HEIGHT] != nil) {
                   return [(NSNumber *)[dic objectForKey:ITEM_HEIGHT] floatValue] +10;
               }
        }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _currentSelectIndex = [indexPath copy];
    NSMutableDictionary *dic = [self.postContentArray objectAtIndex:[indexPath row]];
    if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"text"]) {
        
        //文字反选效果
        UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
        CLTextLayoutLabel *label = (CLTextLayoutLabel *)[cell.contentView viewWithTag:1102];
        label.backgroundColor = [UIColor blackColor];
        label.textColor = [UIColor whiteColor];
        
        UIActionSheet *actionSheet1 = [[[UIActionSheet alloc] initWithTitle:@"文本操作"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:@"复制段落"
                                                        otherButtonTitles:@"复制全文",nil] autorelease];
        actionSheet1.actionSheetStyle = UIBarStyleBlackTranslucent;
        [actionSheet1 showInView:self.view];
 
    }else{
        if ([[dic objectForKey:ITEM_DOWNLOAD_STATE] isEqualToString:DOWNLOADOVER]) {
            UIActionSheet *actionSheet = [[[UIActionSheet alloc] initWithTitle:@"图片操作"
                                                                     delegate:self
                                                            cancelButtonTitle:@"取消"
                                                       destructiveButtonTitle:@"复制剪切板"
                                                            otherButtonTitles:@"保存到相册",@"下载原始图并保存",nil] autorelease];
            actionSheet.actionSheetStyle = UIBarStyleBlackTranslucent;
            [actionSheet showInView:self.view];
        }
 
    }
    

    /*
    currentSelectPicIndex = indexPath.row;
    NSMutableDictionary *dic = [self.postContentArray objectAtIndex:[indexPath row]];
     if ([[dic objectForKey:ITEM_DOWNLOAD_STATE] isEqualToString:DOWNLOADOVER]) {
         //启动图片浏览器
         MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
         browser.wantsFullScreenLayout = NO; // Decide if you want the photo browser full screen, i.e. whether the status bar is affected (defaults to YES)
         browser.displayActionButton = YES; // Show action button to save, copy or email photos (defaults to NO)
         [browser setInitialPageIndex:0];
         [self.navigationController pushViewController:browser animated:YES];
//         [self.navigationController presentModalViewController:browser animated:YES];
//         [self presentModalViewController:browser animated:YES];
         [browser release];
     }
*/
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([self.postContentArray count] > 0)
    {
        NSArray *visiblePaths = [self.postsTableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            
            NSMutableDictionary *dic = [self.postContentArray objectAtIndex:[indexPath row]];
             if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"image"]) {
                 //下载状态判断
                 NSString *downloadState = (NSString *)[dic objectForKey:ITEM_DOWNLOAD_STATE];
                 UITableViewCell *cell = [self.postsTableView cellForRowAtIndexPath:indexPath];
                 UIImageView *imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
                 //如果已下载完成则直接显示图片
                 if ([downloadState isEqualToString:DOWNLOADOVER] || [downloadState isEqualToString:DOWNLOADFAILS]) {
                     imageview = (UIImageView *)[cell.contentView viewWithTag:1101];
                     UIImage *downloadImage = [dic objectForKey:ITEM_IMAGE];
                     //从图片中移除下载进度条
                     UIProgressView *progressView = (UIProgressView *)[imageview viewWithTag:1103];
                     [progressView removeFromSuperview];
                     if (downloadImage != nil) {
                         float width = [[UIScreen mainScreen] bounds].size.width;
                         float height = [(NSNumber *)[dic objectForKey:ITEM_HEIGHT] floatValue];
                         imageview.frame = CGRectMake(0.0f, 10.0f, width, height);
                         imageview.image  = downloadImage;
                     }
                 }
                 //如果未下载图片则开始启动下载
                 if ([downloadState isEqualToString:DOWNLOADBEGIN]) {
                     imageview.frame = defaultImageFrame;
                     imageview.image = [UIImage imageNamed:image_placeholder];
                     
                     NSString *imageUrl = [dic objectForKey:ITEM_CONTENT];
                     NSURL *url =[NSURL URLWithString:imageUrl];
                     //是否是gif图
                     if ([[[url pathExtension] lowercaseString] isEqualToString:@"gif"]) {
                         [dic setValue:@"1" forKey:ITEM_ISGIF];
                     }
                     UIProgressView *progressView = [[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar] autorelease];
                     progressView.hidden=YES;
                     progressView.tag= 1103;
                     progressView.frame = CGRectMake(28 ,imageview.frame.size.height / 2 + 10,100,25);
                     progressView.progress=0.0f;
                     [progressView setHidden:NO];
                     [imageview addSubview:progressView];
                     //保存此imageview
                     [dic setValue:imageview forKey:ITEM_IMAGEVIEW];
                     //标识此图片进入下载中
                     [dic setValue:DOWNLOADING forKey:ITEM_DOWNLOAD_STATE];
                     [dic setValue:progressView forKey:ITEM_DOWNLOAD_PROGRCESSBAR];
                     [self.postContentArray replaceObjectAtIndex:[indexPath row] withObject:dic];
                     //============ASIHTTPRequest==========
                     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
                     request.delegate = self;
                     request.downloadProgressDelegate = progressView;
                     [request setUserInfo:[NSDictionary dictionaryWithObject:indexPath forKey:@"index"]];
                     [self.queue addOperation:request];
                     //================================
               }
             }
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.cNavigationBar.frame = CGRectMake(0, 0, 320, 44);
        }];
    }
}


-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    
    if (velocity.y == 0) {
        [UIView animateWithDuration:0.5 animations:^{
             self.cNavigationBar.frame = CGRectMake(0, 0, 320, 44);
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            self.cNavigationBar.frame = CGRectMake(0, -44, 320, 44);
        }];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}

//双击隐藏导航栏

-(void)handelPan:(UITapGestureRecognizer*)recognizer
{
    /*
        if (hiddenNavagationBar) {
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            hiddenNavagationBar = NO;
        }else{
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            hiddenNavagationBar = YES;
        }
     */
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark -
#pragma mark UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([actionSheet.title isEqualToString:@"文本操作"]) {
        if (buttonIndex == 0) {
            NSString *stringContent = [(NSDictionary *)[self.postContentArray objectAtIndex:self.currentSelectIndex.row] objectForKey:ITEM_CONTENT];
            [[UIPasteboard generalPasteboard] setString:stringContent];
        }
        if (buttonIndex == 1) {
            NSMutableString *allString = [NSMutableString string];
            [self.postContentArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSDictionary *dic = (NSDictionary *)obj;
                if ([[dic objectForKey:ITEM_ATTRIBUTE] isEqualToString:@"text"]) {
                    [allString appendString:[dic objectForKey:ITEM_CONTENT]];
                }
            }];
            [[UIPasteboard generalPasteboard] setString:allString];
        }
        //取消反白效果
        UITableViewCell *cell = [self.postsTableView cellForRowAtIndexPath:self.currentSelectIndex];
        CLTextLayoutLabel *label = (CLTextLayoutLabel *)[cell.contentView viewWithTag:1102];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor colorWithHex:0x454545];
    }

     if([actionSheet.title isEqualToString:@"图片操作"]){
    
        if (buttonIndex == 0)
        {
            UIImage *image = [(NSDictionary *)[self.postContentArray objectAtIndex:[self.currentSelectIndex row]] objectForKey:ITEM_IMAGE];
            [[UIPasteboard generalPasteboard] setData:UIImagePNGRepresentation(image) forPasteboardType:@"public.png"];
            [self performSelectorOnMainThread:@selector(showProgressHUDCompleteMessage:) withObject:@"图片已复制"  waitUntilDone:YES];
        }
        
        if (buttonIndex == 1)
        {
            //保存已显示图片
            UIImage *image = [(NSDictionary *)[self.postContentArray objectAtIndex:_currentSelectIndex.row] objectForKey:ITEM_IMAGE];
            UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),nil);
        }
        if (buttonIndex == 2){
            //保存原始图片（未缩放）
            NSString *imageUrl = [(NSDictionary *)[self.postContentArray objectAtIndex:_currentSelectIndex.row] objectForKey:ITEM_CONTENT];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
            request.delegate = self;
            [request setUserInfo:[NSDictionary dictionaryWithObject:@"1" forKey:@"forSave"]];
            [self.queue addOperation:request];
            
        }
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [self performSelectorOnMainThread:@selector(showProgressHUDCompleteMessage:) withObject:@"图片保存失败"  waitUntilDone:YES]; 
    }else{
        [self performSelectorOnMainThread:@selector(showProgressHUDCompleteMessage:) withObject:@"图片已保存!"  waitUntilDone:YES];  
    }
}
#pragma mark - CLSlideEffectWindowDelegate
#pragma mark  

-(void)slideOver
{
    for (ASIHTTPRequest *req in [self.queue operations]) {
        [req clearDelegatesAndCancel];
        [req setDelegate:nil];
        [req setDidFailSelector:nil];
        [req setDidFinishSelector:nil];
    }
    [self.queue cancelAllOperations];
    [self.queue setDelegate:nil];
    [self.cNavigationBar setHidden:YES];

}

#pragma mark -
#pragma mark UIAlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    [NSThread detachNewThreadSelector:@selector(readPostContent) toTarget:self withObject:nil];
}

-(void)resetImageCellContent:(ASIHTTPRequest *)request
{
    NSIndexPath *index =  (NSIndexPath *) [request.userInfo objectForKey:@"index"];
    NSMutableDictionary *dic = (NSMutableDictionary *) [self.postContentArray objectAtIndex:[index row]];
    if (dic != nil) {

        UIProgressView *progressbar = [dic objectForKey:ITEM_DOWNLOAD_PROGRCESSBAR];
        NSData * data=[request responseData];
        
        UIImage *downloadImage;
        if ([[dic objectForKey:ITEM_ISGIF] isEqualToString:@"1"]) {
           downloadImage =  [UIImage animatedImageWithAnimatedGIFData:data];
            [dic setValue:[NSNumber numberWithFloat:downloadImage.size.height] forKey:ITEM_HEIGHT];
        }else{
            downloadImage = [UIImage imageWithData:data];
            //某些时候会出现downloadImage为空的情况，这种情况当下载失败处理
            if (downloadImage == nil) {
                downloadImage = [UIImage imageNamed:@"downloadFails.png"]; 
            }
            //计算图片调整后的大小
            float width = [[UIScreen mainScreen] bounds].size.width;
            //缩放图片到适合屏幕宽度
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.f, 0.f, width,downloadImage.size.height)];
            imageview.contentMode = UIViewContentModeScaleAspectFit;
            imageview.image =downloadImage;
            CGRect t = [self frameForImage:downloadImage inImageViewAspectFit:imageview];
            [imageview release];
            downloadImage = [downloadImage scaleToSize:CGSizeMake(t.size.width * 2, t.size.height *2)];
             [dic setValue:[NSNumber numberWithFloat:t.size.height] forKey:ITEM_HEIGHT];
        }
       

        [dic setValue:DOWNLOADOVER forKey:ITEM_DOWNLOAD_STATE];
        [dic setValue:downloadImage forKey:ITEM_IMAGE];
        [self.postContentArray replaceObjectAtIndex:[index row] withObject:dic];
        
             progressbar.hidden = YES;
    }
    [self performSelectorOnMainThread:@selector(reloadData:) withObject:index waitUntilDone:YES];
 
}

-(void)reloadData:(NSIndexPath*)index
{
//    [self.postsTableView reloadData];
    [self.postsTableView beginUpdates];
      [self.postsTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.postsTableView endUpdates];
}
//保存原始图
-(void)saveBigImage:(ASIHTTPRequest *)request
{
    NSData * data=[request responseData];
    UIImage *downloadImage = [UIImage imageWithData:data];
    UIImageWriteToSavedPhotosAlbum(downloadImage,self,@selector(image:didFinishSavingWithError:contextInfo:),nil); 
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request{
    //forsave标记标识下载的图片是用来保存用（原始图）
    if ([[[request userInfo] objectForKey:@"forSave"] isEqualToString:@"1"]) {
        [NSThread detachNewThreadSelector:@selector(saveBigImage:) toTarget:self withObject:request];
    }else{
         [NSThread detachNewThreadSelector:@selector(resetImageCellContent:) toTarget:self withObject:request];
    }
  
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSIndexPath *index =  (NSIndexPath *) [request.userInfo objectForKey:@"index"];
    NSMutableDictionary *dic = (NSMutableDictionary *) [self.postContentArray objectAtIndex:[index row]];
    if (dic != nil) {
        UIProgressView *progressbar = [dic objectForKey:ITEM_DOWNLOAD_PROGRCESSBAR];
        UIImage *errorImage = [UIImage imageNamed:@"downloadFails.png"];
        progressbar.hidden = YES;
        [dic setValue:[NSNumber numberWithFloat:errorImage.size.height] forKey:ITEM_HEIGHT];
        [dic setValue:DOWNLOADFAILS forKey:ITEM_DOWNLOAD_STATE];
        [dic setValue:errorImage forKey:ITEM_IMAGE];
        [self.postContentArray replaceObjectAtIndex:[index row] withObject:dic];
    }
    [self reloadData:index];
}




#pragma mark -
-(void)readPostContent
{
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tiezi.html" ofType:nil];
//    NSString *response =  [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
//    response = [response stringByReplacingOccurrencesOfString:@"gb2312" withString:@"utf-8"];
//   NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"%@",str);
    NSString *response = [CLTool getCLResponseString:self.fullURL andCurrentView:self.view];
    
    //网络异常处理
    if ([response isEqualToString:@"error"] || response == nil) {
        [self performSelectorOnMainThread:@selector(showAlert) withObject:nil waitUntilDone:NO];
         return;
    }
    self.postContentData = [response dataUsingEncoding:NSUTF8StringEncoding];
    TFHpple *doc = [[TFHpple alloc] initWithHTMLData:self.postContentData];
    
   //楼主名抓取
    TFHppleElement *e1 = [doc peekAtSearchWithXPathQuery:TOP_AUTHOR_NAME_QUERY];
    NSString *authorStr = [e1 content];
    NSLog(@"楼主:%@",authorStr);
    //发帖时间抓取
    TFHppleElement *e2 = [doc peekAtSearchWithXPathQuery:TOP_POSTED_TIME_QUERY];
    NSString *timeStr = [[e2 content] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"发帖时间:%@",timeStr);
//    [e2 content]
    
    //楼主贴内容抓取
    NSArray * array = [doc searchWithXPathQuery:TOP_POST_CONTENT_QUERY];
    //获取所有链接的href值
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TFHppleElement *e = (TFHppleElement *)obj;
        if ([e objectForKey:@"src"] == nil) {
            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
            [tmp setObject:@"text" forKey:ITEM_ATTRIBUTE];
            //判断不是空行则加入到字典中
            if ([[[e content] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] != 0) {
                [tmp setObject:[e content] forKey:ITEM_CONTENT];
            }
           //在此处把文字占用的高度计算出来(废弃)
//            CGSize size = [[e content] sizeWithFont:systemFont constrainedToSize:CGSizeMake(310.0, 2000.0) lineBreakMode:UILineBreakModeWordWrap];
//            CGSize size = [[e content] sizeWithFont:kHSCNBoldFont16 constrainedToSize:CGSizeMake(310.0, 2000.0) lineBreakMode:UILineBreakModeWordWrap];
//            CGFloat height =MAX(size.height + 5  , 44.0f);
            
            //=======计算label所占用的高度======
            CLTextLayoutLabel *cltext = [[CLTextLayoutLabel alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            cltext.text = [e content];
            cltext.font = kHSCNBoldFont16;
            [cltext setLinesSpacing:8.0f];
            CGFloat height = [cltext getAttributedStringHeight:LABLE_CONTENT_WIDTH];
            [cltext release];
            //===========================
            [tmp setValue:[NSNumber numberWithFloat:height] forKey:ITEM_HEIGHT];
                      [self.postContentArray addObject:tmp];
//            NSLog(@"text:%@",[e content]);
        }else{
            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
            NSString *imageSrc = [e objectForKey:@"src"];
            [tmp setObject:@"image" forKey:ITEM_ATTRIBUTE];
            [tmp setObject:imageSrc forKey:ITEM_CONTENT];
            [tmp setObject:DOWNLOADBEGIN forKey:ITEM_DOWNLOAD_STATE];
       
            [self.postContentArray addObject:tmp];
//            NSLog(@"src:%@",[e objectForKey:@"src"]);
               }
    }];
    [doc release];
    [self performSelectorOnMainThread:@selector(tableviewReload) withObject:nil waitUntilDone:NO];
}

//重新加载表格
-(void)tableviewReload
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    [self.postsTableView reloadData];
}


//此方法作用是得出一个UiImage缩放到imageView后，这个imageview实际的CGRect值
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
    float imageRatio = image.size.width / image.size.height;
    float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
    if(imageRatio < viewRatio)
    {
        float scale = imageView.frame.size.height / image.size.height;
        float width = scale * image.size.width;
        float topLeftX = (imageView.frame.size.width - width) * 0.5;
        return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
    }
    else
    {
        float scale = imageView.frame.size.width / image.size.width;
        float height = scale * image.size.height;
        float topLeftY = (imageView.frame.size.height - height) * 0.5;
        return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
    }
}


-(IBAction)clickReadLater
{
    NSString *username  =  [[NSUserDefaults  standardUserDefaults] objectForKey:@"InstapaperUser"];
    NSString *password =  [[NSUserDefaults  standardUserDefaults] objectForKey:@"InstapaperPassword"];
    if (username == nil || password ==  nil || [username length] == 0 || [password length] == 0) {
        [self showProgressHUDCompleteMessage:@"错误:没有设置用户名或密码"];
    }else{
        BOOL result = [CLTool addPostToInstapaperWithTitle:self.postTitle withUrl:self.fullURL withUserName:username withPassword:password];
        if (result) {
             [self showProgressHUDCompleteMessage:@"已添加到Instapaper"]; 
        }
    }
}


-(IBAction)backAction
{
//    NSNotification *notification = [NSNotification notificationWithName:CL_closeWindows_NotifiationName object:nil];
//    [[NSNotificationCenter defaultCenter] postNotification:notification];
    [self slideOver];
    [self.navigationController popViewControllerAnimated:YES];
}

-(IBAction)replayPostAction
{
    TFHpple *doc = [[TFHpple alloc] initWithHTMLData:self.postContentData];
    NSArray * array = [doc searchWithXPathQuery:REPLAY_POST_CONTENT_QUERY];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TFHppleElement *e = (TFHppleElement *)obj;
        NSString *replayPost = [[e content] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSLog(@"replay post:%@",replayPost);
        [self.replayPostArray addObject:replayPost];
    }];
    
    CLReplyPostsViewController *vc = [[CLReplyPostsViewController alloc] init];
    vc.replyPosts = self.replayPostArray;
    
    CLAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    CLSlideEffectWindow *window = delegate.replayPostsWindow;
    window.prevWindow = delegate.contentWindow;
    [window setRootViewController:vc];
    [window makeKeyAndVisible];
 
    [UIView animateWithDuration:0.3 animations:^{
        [window setFrame:[[UIScreen mainScreen] bounds]];
    } completion:^(BOOL finished) {
    }];

    
}

-(void)openWebview
{
    CLWebViewController *webvc = [[CLWebViewController alloc] initWithNibName:@"CLWebViewController" bundle:nil];
    webvc.urlString = self.fullURL;
    [self.navigationController pushViewController:webvc animated:YES];
    [webvc release];
}

-(void)showAlert
{
    /*
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络访问失败"
                                                    message:@"网络访问失败，内容不能正常显示"
                                                   delegate:self
                                          cancelButtonTitle:@"重试"
                                          otherButtonTitles:@"取消",nil];
    [alert show];
    [alert release];
     */
    [self showProgressHUDCompleteMessage:@"网络访问失败，内容不能正常显示"];
}

- (void)showProgressHUDCompleteMessage:(NSString *)message {
    MBProgressHUD *progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (message) {
        if (progress.isHidden) [progress show:YES];
        progress.labelText = message;
        progress.mode = MBProgressHUDModeCustomView;
        [progress hide:YES afterDelay:1.5];
    } else {
        [progress hide:YES];
    }
}

-(void)dealloc
{
    [_currentSelectIndex release];
    [self.queue setDelegate:nil];
    [self.queue cancelAllOperations];
//    [_queue release];
//    self.queue = nil;
    [_louzhuName release];
    [_postedTime release];
    [_imageViewDic release];
    [_progress release];
    [_fullURL release];
    [_postContentArray removeAllObjects];
    [_postContentArray release];
    [_postsTableView release];
    [_cNavigationBar release];
    [_toolbar release];
    [_postContentData release];
    [_repostButton release];
    [super dealloc];
}
- (void)viewDidUnload {
    self.currentSelectIndex = nil;
    self.postContentArray = nil;
    [self setPostsTableView:nil];
    [self setCNavigationBar:nil];
    [self setToolbar:nil];
    [self setRepostButton:nil];
    [super viewDidUnload];
}
@end
